package de.g18.it0a.jlaser.solution;

import java.util.Vector;

import de.g18.it0a.jlaser.domain.LaserConfiguration;
import de.g18.it0a.jlaser.domain.Line;
import de.g18.it0a.jlaser.domain.Mirror;
import de.g18.it0a.jlaser.domain.Position;
import de.g18.it0a.jlaser.domain.RoomConfiguration;
import de.g18.it0a.jlaser.domain.Tile;


public class SolutionChecker {

    private final RoomConfiguration roomConfig;
    private final LaserConfiguration laserConfig;

    private final SolutionHelper helper;


    public SolutionChecker(RoomConfiguration aRoomConfig, LaserConfiguration aLaserConfig) {
        roomConfig = aRoomConfig;
        laserConfig = aLaserConfig;
        helper = SolutionHelper.getInstance(aRoomConfig);
    }

    public boolean isSolution() {
        Vector<Tile> uncrossedTiles = new Vector<Tile>(helper.getTilesToBeCrossed());
        Position lastPosition = laserConfig.getStart();
        for (Mirror mirror : laserConfig.getMirrors()) {
            Line line = new Line(lastPosition, mirror.getPosition());
//            if (!helper.isValidConnection(line)) {
//                return false;
//            }
//            for (Iterator<Tile> it = uncrossedTiles.iterator(); it.hasNext();) {
//                if (LineUtil.intersects(line, it.next())) {
//                    it.remove();
//                }
//            }
            uncrossedTiles.removeAll(SolutionHelper.getInstance(roomConfig).getTilesCrossedBy(line));
            if (uncrossedTiles.isEmpty()) {
                return true;
            }
            lastPosition = mirror.getPosition();
        }

        if (laserConfig.getEnd() != null) {
            Line line = new Line(lastPosition, laserConfig.getEnd());
            uncrossedTiles.removeAll(SolutionHelper.getInstance(roomConfig).getTilesCrossedBy(line));
            if (uncrossedTiles.isEmpty()) {
                return true;
            }
        }
        return uncrossedTiles.isEmpty();
    }
}